import React, { useEffect, useRef, useState } from 'react';
import {
  Table,
  TableColumnProps,
  Space,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Drawer,
  Modal,
  Message,
} from '@arco-design/web-react';
import { validatePhone } from '@/utils/formValidate';
import { statusOptions } from '@/pages/userManagement/backendUserList/common';
import { IconEdit, IconSearch } from '@arco-design/web-react/icon';

const FormItem = Form.Item;
const Option = Select.Option;

function FormBox(props: any) {
  const {
    visible,
    handleChangeVisible,
    modalTitle,
    relationUserList,
    editData,
    formModalShowType,
  } = props;
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isWork, setIsWork] = useState(true);
  const [selectAccountVisible, setSelectAccountVisible] = useState(false);
  const [selectedAccountRowKeys, setSelectedAccountRowKeys] = useState([]);
  const [selectedAccount, setSelectedAccount] = useState(null);

  useEffect(() => {
    if (!visible) return;
    form.resetFields();
    form.setFieldsValue(editData);
    if (formModalShowType === 'edit') {
      setIsWork(editData.Status === 1);
      setSelectedRowKeys(editData.RelationUserIds);
      getSelectedAccountLabel(editData.CTLUserId);
    } else {
      setIsWork(true);
      setSelectedRowKeys([]);
      setSelectedAccount(null);
    }
  }, [visible]);

  const getSelectedAccountLabel = (CTLUserId: string) => {
    const account = relationUserList.find(
      (Item) => Item.CTLUserId === CTLUserId
    );
    setSelectedAccount(account);
  };

  const onOk = () => {
    form.validate().then((value) => {
      if (!selectedAccount) {
        Message.error('请选择关联校园账号');
        return;
      }
      props.onConfirm &&
        props.onConfirm(
          {
            ...props.editData,
            ...value,
            RelationUserIds: selectedRowKeys,
            CTLUserId: selectedAccount.CTLUserId,
          },
          relationUserList
        );
    });
  };

  const onCancel = () => {
    props.onCancel && props.onCancel();
    form.resetFields();
    handleChangeVisible(false);
  };

  const statusChange = (value: number) => {
    setIsWork(value === 1);
    if (value === 2) {
      // 将离职日期设置为今天的时间
      form.setFieldsValue({ ResignDate: new Date() });
    }
  };
  const inputRef1 = useRef(null);
  const inputRef2 = useRef(null);

  const columns: TableColumnProps[] = [
    {
      title: '校园账号',
      dataIndex: 'CTLAccount',
      align: 'center',
      filterIcon: <IconSearch />,
      filterDropdown: ({ filterKeys, setFilterKeys, confirm }) => {
        return (
          <div className="arco-table-custom-filter">
            <Input.Search
              ref={inputRef1}
              searchButton
              placeholder="请输入账号"
              value={filterKeys[0] || ''}
              onChange={(value) => {
                setFilterKeys(value ? [value] : []);
              }}
              onSearch={() => {
                confirm();
              }}
            />
          </div>
        );
      },
      onFilter: (value, row) =>
        value ? row.CTLAccount.indexOf(value) !== -1 : true,
      onFilterDropdownVisibleChange: (visible) => {
        if (visible) {
          setTimeout(() => inputRef1.current.focus(), 150);
        }
      },
    },
    {
      title: 'C端用户名',
      dataIndex: 'CTLUserName',
      align: 'center',
      filterIcon: <IconSearch />,
      filterDropdown: ({ filterKeys, setFilterKeys, confirm }) => {
        return (
          <div className="arco-table-custom-filter">
            <Input.Search
              ref={inputRef2}
              searchButton
              placeholder="请输入用户名"
              value={filterKeys[0] || ''}
              onChange={(value) => {
                setFilterKeys(value ? [value] : []);
              }}
              onSearch={() => {
                confirm();
              }}
            />
          </div>
        );
      },
      onFilter: (value, row) =>
        value ? row.CTLUserName.indexOf(value) !== -1 : true,
      onFilterDropdownVisibleChange: (visible) => {
        if (visible) {
          setTimeout(() => inputRef2.current.focus(), 150);
        }
      },
    },
  ];

  const selectAccountOnOk = () => {
    setSelectAccountVisible(false);
    getSelectedAccountLabel(selectedAccountRowKeys[0]);
  };


  return (
    <>
      <Drawer
        title={modalTitle}
        visible={visible}
        onCancel={onCancel}
        autoFocus={false}
        focusLock={false}
        style={{ width: '650px' }}
        footer={
          <Space size="small">
            <Button type="primary" onClick={onOk}>
              保存
            </Button>
          </Space>
        }
      >
        <Form form={form}>
          <FormItem
            label="用户账号"
            field="Account"
            rules={[{ required: true, message: '请输入用户账号' }]}
          >
            <Input
              placeholder="请输入"
              disabled={formModalShowType === 'edit'}
              autoComplete={'off'}
            />
          </FormItem>
          <FormItem
            label="用户名称"
            field="Name"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入" autoComplete={'off'} />
          </FormItem>
          <FormItem
            label="手机号"
            field="PhoneNumber"
            rules={[{ required: true, validator: validatePhone }]}
          >
            <Input placeholder="请输入" autoComplete={'off'} />
          </FormItem>
          <FormItem
            label="状态"
            field="Status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select
              options={statusOptions}
              onChange={statusChange}
              disabled={formModalShowType === 'add'}
            ></Select>
          </FormItem>
          {isWork ? (
            <FormItem
              label="关联校园账号"
              rules={[{ required: true, message: '请选择关联校园账号' }]}
            >
              {/*<Select>
              {relationUserList.map((option, index) => (
                <Option key={option.CTLUserId} value={option.CTLUserId}>
                  {option.CTLAccount + ' - ' + option.CTLUserName}
                </Option>
              ))}
            </Select>*/}

              {!!selectedAccount ? (
                <span>
                  {selectedAccount.CTLUserName}
                  <IconEdit
                    onClick={() => {
                      setSelectAccountVisible(true);
                      setSelectedAccountRowKeys([selectedAccount.CTLUserId]);
                    }}
                    style={{ marginLeft: 5, fontSize: 16, cursor: 'pointer' }}
                  />
                </span>
              ) : (
                <Button
                  type="secondary"
                  onClick={() => {
                    setSelectAccountVisible(true);
                    setSelectedAccountRowKeys([]);
                  }}
                >
                  选择子账号
                </Button>
              )}
            </FormItem>
          ) : (
            <FormItem
              label="离职日期"
              field="ResignDate"
              rules={[{ required: true, message: '请选择离职日期' }]}
            >
              <DatePicker />
            </FormItem>
          )}
        </Form>
        <div>
          <div>管控账户</div>
          <Table
            borderCell
            border
            rowKey="CTLUserId"
            columns={columns}
            data={relationUserList}
            pagination={false}
            rowSelection={{
              type: 'checkbox',
              selectedRowKeys,
              onChange: (selectedRowKeys, selectedRows) => {
                setSelectedRowKeys(selectedRowKeys);
              },
            }}
            scroll={{
              y: 460,
            }}
          />
        </div>
      </Drawer>

      <Modal
        title="校园账号列表"
        visible={selectAccountVisible}
        onCancel={() => {
          setSelectAccountVisible(false);
        }}
        onOk={selectAccountOnOk}
        focusLock={false}
        style={{ width: '600px' }}
      >
        <Table
          borderCell
          border
          rowKey="CTLUserId"
          columns={columns}
          data={relationUserList}
          pagination={false}
          rowSelection={{
            type: 'radio',
            selectedRowKeys: selectedAccountRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedAccountRowKeys(selectedRowKeys);
            },
          }}
          scroll={{
            y: 460,
          }}
        />
      </Modal>
    </>
  );
}

export default FormBox;
